import React,{Component} from 'react'
import axios from 'axios'
import {Input,Form,Button,Select} from 'antd'
import classNames from 'classnames/bind'
import styles from './editform.scss'
import { ContentState} from 'draft-js'
import { Editor } from 'react-draft-wysiwyg'
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css'
import {connect} from 'react-redux'
import {EDIT_CONTENTSTATE} from '../../util'
import draftToHtml from 'draftjs-to-html'
import htmlToDraft from 'html-to-draftjs'
import {API_ADDRESS} from '../../util/address';




const Option = Select.Option;
const FormItem = Form.Item;
const cx=classNames.bind(styles);



function hasErrors(fieldsError) {
  return Object.keys(fieldsError).some(field => fieldsError[field]);
}
function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}


class EditForm extends Component{

  constructor(props){
    super(props)
    this.state={
      contentid:undefined,
      contentState:EDIT_CONTENTSTATE};

  }

  componentWillMount(){

    const {contentid,contentState}=this.props
    //如果无id且本地有数据，从props拿数据
    //如果有id，直接从props中拿数据
    if(contentid===undefined)
    {
      const content=window.localStorage.getItem('content')//从本地获取数据
      if(content){
         const c=JSON.parse(content)
         this.setState({contentState:c})
      }
     }
     else
     {
      this.setState({contentState,contentid})
     }
  }

  componentDidMount(){
    if(this.state.contentid===undefined)
    {
      this.timer=setInterval(() => {
        const {contentState}=this.state;
        window.localStorage.setItem('content', JSON.stringify(contentState));
      }, 5000);
    }
  }
  componentWillUnmount()
  {
    clearInterval(this.timer);
  }

  onContentStateChange(contentState){
    this.setState({contentState})
  }


  handlePost(posted){
    //保存：将数据发送到后台并将本地文件清除，posted为0
    //发布：posted为1
    //如果是insert，清除本地数据
    const {contentState}=this.state;
    const content=draftToHtml(contentState)
     this.props.form.validateFields(async (err, values) => {
       if (!err) {
         let title=values.title;
         let moduleName=values.moduleName;
         let contentid=this.state.contentid;
         let options = {
                    title,
                    content,
                    moduleName,
                    posted,
                    contentid
                }
          const {data}=await axios.post(`${API_ADDRESS}/savedoc`,options);
          if(data.update==='ok'||data.insert)//insert返回id
          {
            window.localStorage.removeItem('content');
            alert('操作成功！')
            const {data}=await axios.get(`${API_ADDRESS}/getMes`);
            this.props.onChangeStore({type:'update',data:{data}})
          }
       }
     });
  }
  handleSave(){
    this.handlePost(false);
  }
  handleSubmit(e){
    e.preventDefault();
    this.handlePost(true);
  }
 async handleDel(){
  let contentid=this.state.contentid
  let options = {
      contentid
  }
  const {data}=await axios.post(`${API_ADDRESS}/del`,options);
  if(data.delete==='ok')
  {
    alert('删除成功！')
    const {data}=await axios.get(`${API_ADDRESS}/getMes`);
    this.props.onChangeStore({type:'update',data:{data}})
  }
  else{
    alert("操作失败！请稍后再试")
  }
 }



  async uploadImageCallBack(file) {
    //{data: { link: <THE_URL>}}
    let options = {
      headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
      },
      body:{}
    }
    const {data:{uptoken,key}}= await axios.post(`${API_ADDRESS}/getQiniuToken`,options)
    const formData = new FormData();
        formData.append('file', file);
        formData.append('key',key);
        formData.append('token',uptoken);
    const {data:{src}}=await axios.post('https://up-z2.qiniup.com',formData)
    return new Promise((resolve,reject)=>{return resolve({data: { link:src}})})
  }

  render(){
    const { contentState} = this.state;
    const { getFieldDecorator, getFieldsError, getFieldError, isFieldTouched,setFieldsValue} = this.props.form;
    return (
      <div>
    <Form layout='inline' onSubmit={this.handleSubmit.bind(this)}>

      <FormItem
      label="文档标题"
      >
          {getFieldDecorator('title', {
            rules: [{ required: true, message: '文档标题为必填项!' }],
          })(
            <Input placeholder="请输入文档标题"/>
          )}
        </FormItem>

        <FormItem
        label="文档分类"
        hasFeedback
        >
        {getFieldDecorator('moduleName', {
            rules: [{ required: true,message: '文档模块为必选项!' }],
          })
        (
          <Select style={{ width: 120 }}>
            <Option value="employee">员工</Option>
            <Option value="insurance">社保</Option>
            <Option value="attendance">考勤</Option>
            <Option value="salary">薪酬</Option>
            <Option value="process">流程</Option>
            <Option value="analysis">统计分析</Option>
            <Option value="setting">系统设置</Option>
          </Select>
        )
        }
        </FormItem>

        <Editor
          initialContentState={contentState}
          wrapperClassName={cx("editor-wrapper")}
          editorClassName={cx("editor-editor")}
          toolbarClassName={cx("editor-toolbar")}
          toolbar={{
            options: ['inline', 'blockType', 'fontSize', 'fontFamily', 'list', 'textAlign', 'link', 'colorPicker','emoji', 'image', 'history'],
            inline: { inDropdown: true },
            list: { inDropdown: true },
            textAlign: { inDropdown: true },
            link: { inDropdown: true },
            image: { previewImage: true,
                    uploadCallback: this.uploadImageCallBack,
                    alt: { present: false, mandatory: false },
                    defaultSize: {
                            height: '100%',
                            width: '100%',
                          },
                    },
          }}
          onContentStateChange={this.onContentStateChange.bind(this)}
      />

        <Button
        onClick={this.handleSave.bind(this)}
        disabled={hasErrors(getFieldsError())}
        >
        存入草稿箱
        </Button>

        <Button
        htmlType="submit"
        disabled={hasErrors(getFieldsError())}
        >
        发布文档
        </Button>

        <Button
        onClick={this.handleDel.bind(this)}
        disabled={hasErrors(getFieldsError())}
        >
        删除文档
        </Button>

        </Form>
      </div>
        )
  }
}


 EditForm=Form.create({
  mapPropsToFields(props){
    const title=props.title
    const moduleName=props.moduleName
    return {
      title: Form.createFormField({
        value:title,
      }),
      moduleName: Form.createFormField({
        value:moduleName,
      }),
    };
  },
 })(EditForm)

export default connect(
  state=>({data:state.data}),
  dispatch=>({onChangeStore:(options)=>{
    dispatch({type:options.type,data:options.data})
  }})
)(EditForm)
